package vn.ikame.android.boojtran.truyenbua;

import java.util.ArrayList;

import vn.ikame.android.boojtran.truyenbua.download.ItemListDowloadListener;
import vn.ikame.android.boojtran.truyenbua.download.ItemListDownload;
import vn.ikame.android.boojtran.truyenbua.object.GA;
import vn.ikame.android.boojtran.truyenbua.object.Item;
import vn.ikame.android.boojtran.truyenbua.object.PicView;
import vn.ikame.android.boojtran.truyenbua.utility.CConstant;
import vn.ikame.android.boojtran.truyenbua.utility.ItemManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class Viewer extends SuperActivity implements AnimationListener,
		ItemListDowloadListener {
	final Handler myHandler = new Handler();
	public String photoUrl;
	private AdView adView;
	private TextView txtHeader, txtFooter;
	private Animation headerAnim, footerAnim;

	private ViewPager viewPager;
	private PicViewPagerAdapter pagerAdapter;
	private OnPageChangeListener onPageChange;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.viewer);
		if (ItemManager.getInstance().getListItem() == null
				|| ItemManager.getInstance().getListItem().size() <= 0) {
			startActivity(new Intent(Viewer.this, Splash.class));
			this.finish();
		} else {
			txtHeader = (TextView) findViewById(R.id.txt_header);
			txtFooter = (TextView) findViewById(R.id.txt_footer);
			headerAnim = AnimationUtils.loadAnimation(this, R.anim.anim_header);
			footerAnim = AnimationUtils.loadAnimation(this, R.anim.anim_footer);
			headerAnim.setAnimationListener(this);
			footerAnim.setAnimationListener(this);
			initTextView();

			// admob
			adView = (AdView) this.findViewById(R.id.adView);
			adView.loadAd(new AdRequest());

			pagerAdapter = new PicViewPagerAdapter();
			viewPager = (ViewPager) findViewById(R.id.viewpager);
			viewPager.setAdapter(pagerAdapter);
			onPageChange = new OnPageChangeListener();
			viewPager.setOnPageChangeListener(onPageChange);
			viewPager.setCurrentItem(ItemManager.getInstance()
					.getCurItemIndex());
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			super.onBackPressed();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
	}

	private void initTextView() {
		txtHeader.setText(ItemManager.getInstance().getCurItem().getTitle());
		txtHeader.setVisibility(View.VISIBLE);
		txtHeader.startAnimation(headerAnim);
		txtFooter.setText("Nhớ click quảng cáo ủng hộ nha :D");
		if (viewed % 5 == 0) {
			txtFooter.setVisibility(View.VISIBLE);
			txtFooter.startAnimation(footerAnim);
		}
	}

	private class PicViewPagerAdapter extends PagerAdapter {
		private PicView picView;

		public PicViewPagerAdapter() {
		}

		@Override
		public int getCount() {
			return SuperActivity.totalItem;
		}

		@Override
		public Object instantiateItem(View collection, int pageViewPos) {
			View view = null;
			try {
				LayoutInflater vi = (LayoutInflater) Viewer.this
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.picview, null);

				picView = (PicView) view.findViewById(R.id.viewPhoto);
				picView.init(Viewer.this);
				picView.setImageUrl(ItemManager.getInstance().getLinkImage(
						pageViewPos));
				view.setTag(pageViewPos);
				((ViewPager) collection).addView(view, 0);
			} catch (Exception e) {
				try {
					finish();
					System.gc();
					android.os.Process.killProcess(android.os.Process.myPid());
				} catch (Exception ex) {
				}
			}
			return view;
		}

		/**
		 * Remove a page for the given position. The adapter is responsible for
		 * removing the view from its container, although it only must ensure
		 * this is done by the time it returns from {@link #finishUpdate()}.
		 * 
		 * @param container
		 *            The containing View from which the page will be removed.
		 * @param position
		 *            The page position to be removed.
		 * @param object
		 *            The same object that was returned by
		 *            {@link #instantiateItem(View, int)}.
		 */
		@Override
		public void destroyItem(View collection, int position, Object view) {
			((ViewPager) collection).removeView((View) view);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == ((View) object);
		}

		/**
		 * Called when the a change in the shown pages has been completed. At
		 * this point you must ensure that all of the pages have actually been
		 * added or removed from the container as appropriate.
		 * 
		 * @param container
		 *            The containing View which is displaying this adapter's
		 *            page views.
		 */
		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}

	}

	public class OnPageChangeListener extends
			ViewPager.SimpleOnPageChangeListener {

		private int currentPage;

		@Override
		public void onPageSelected(int position) {
			currentPage = position;
			viewed++;
			if (currentPage >= previousTotal - visibleThreshold
					&& previousTotal < totalItem) {
				requestListItems(CConstant.SVR_IMG_LINK, previousTotal,
						itemCount);
			}
			ItemManager.getInstance().setCurItem(position);
			if (!isBelongIntArray(showedArr,
					ItemManager.getInstance().getItem(position).getId())) {
				showedArr.add(ItemManager.getInstance().getItem(position)
						.getId());
				store.setShowedArr(showedArr);
			}
			try {
				store.setPic(ItemManager.getInstance().getCurItem().getId());
			} catch (Exception e) {
			}
			try {
				initTextView();
			} catch (Exception e) {
			}
			System.out.println("current= "
					+ ItemManager.getInstance().getListItem().get(currentPage)
							.getContent());
		}

		public int getCurrentPage() {
			return currentPage;
		}
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		try {
			txtHeader.setVisibility(View.GONE);
			txtFooter.setVisibility(View.GONE);
			GA.trackDetailView(APP_NAME);
		} catch (Exception e) {
		}
	}

	@Override
	public void onAnimationRepeat(Animation animation) {
	}

	@Override
	public void onAnimationStart(Animation animation) {
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.option_menu, menu);
		menu.removeItem(R.id.refresh);
		menu.removeItem(R.id.bookmark);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case R.id.funstory:
			if (funStories == null || funStories.size() <= 0) {
				requestListItems(CConstant.SVR_FUNSTORY_LINK, storyArr.size(),
						itemCount);
			} else {
				startActivity(new Intent(Viewer.this, FunStory.class));
			}
			break;
		case R.id.share:
			Intent sharingIntent = new Intent(Intent.ACTION_SEND);
			sharingIntent.setType("text/plain");
			sharingIntent
					.putExtra(
							android.content.Intent.EXTRA_TEXT,
							ItemManager.getInstance().getCurLinkImage()
									+ " \n Cười thả ga với Ứng dụng Truyện Bựa 18+ - https://play.google.com/store/apps/details?id="
									+ APP_PACKAGE);
			// sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
			// "Ứng dụng Truyện Bựa 18+ - https://play.google.com/store/apps/details?id="
			// + APP_PACKAGE);
			ComponentName name = new ComponentName(APP_PACKAGE, APP_NAME);
			// sharingIntent.addCategory(Intent.CATEGORY_LAUNCHER);
			// sharingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
			// | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			sharingIntent.setComponent(name);
			startActivity(Intent.createChooser(sharingIntent, "Chia sẻ với"));
			// PackageManager pm = getPackageManager();
			// List<ResolveInfo> activityList = pm.queryIntentActivities(
			// sharingIntent, 0);
			// for (final ResolveInfo app : activityList) {
			// if ((app.activityInfo.name).contains("facebook")) {
			// final ActivityInfo activity = app.activityInfo;
			// break;
			// }
			// }
			break;
		// case R.id.chat:
		// startActivity(new Intent(Viewer.this, ChatActivity.class));
		// break;
		// case R.id.moregame:
		// Intent intent = new Intent(Intent.ACTION_VIEW);
		// intent.setData(Uri.parse("market://search?q=ikame"));
		// startActivity(intent);
		// break;
		// case R.id.rateapp:
		// Intent intent1 = new Intent(Intent.ACTION_VIEW);
		// intent1.setData(Uri.parse("market://details?id=" + APP_PACKAGE));
		// startActivity(intent1);
		// break;
		// case R.id.about:
		// showAboutDialog();
		// break;
		}
		return true;
	}

	@Override
	protected void requestListItems(String svr_link, int start, int count) {
		if (isOnline()) {
			ItemListDownload itemListDownload = new ItemListDownload(this, this);
			itemListDownload.start(svr_link, start, count);
		} else {
			showNetworkDialog();
		}
	}

	@Override
	public void onDownloadFinish(ArrayList<Item> result, String svr_link,
			int start, int count) {
		if (result != null && result.size() > 0) {
			Log.e("TAG", "ok1");
			if (svr_link.equals(CConstant.SVR_IMG_LINK)) {
				ItemManager.getInstance().getListItem().addAll(result);
				previousTotal = start + count;
			} else if (svr_link.equals(CConstant.SVR_FUNSTORY_LINK)) {
				Log.e("TAG", "ok2");
				funStories = result;
				startActivity(new Intent(Viewer.this, FunStory.class));
				Viewer.this.finish();
			}
		} else {
			if (svr_link.equals(CConstant.SVR_IMG_LINK)) {
				GA.trackDetailView(APP_NAME + "_downloadListError");
			} else if (svr_link.equals(CConstant.SVR_FUNSTORY_LINK)) {
				if (result.size() <= 0) {
					storyArr.clear();
					store.setStoryArr(storyArr);
					if (funStories == null || funStories.size() <= 0) {
						requestListItems(CConstant.SVR_FUNSTORY_LINK, 0,
								itemCount);
					} else {
						startActivity(new Intent(Viewer.this, FunStory.class));
					}
				} else {
					GA.trackDetailView(APP_NAME + "_funStoryDownloadListError");
					showReconnectDialog(svr_link, start, count);
					Log.e("TAG", "lose2");
				}
			}
			showReconnectDialog(svr_link, start, count);
			Log.e("TAG", "lose1");
		}
	}

	@Override
	public void onDownloadError(String svr_link, int start, int count) {
		if (svr_link.equals(CConstant.SVR_IMG_LINK)) {
			GA.trackDetailView(APP_NAME + "_downloadListError");
		} else if (svr_link.equals(CConstant.SVR_FUNSTORY_LINK)) {
			GA.trackDetailView(APP_NAME + "_funStoryDownloadListError");
		}
		showReconnectDialog(svr_link, start, count);
	}
}
